﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.SocketEnum;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.SocketModel;
using ZBJF.Warranty.WebProvider;
using ZBJF.Warranty.WeiXin;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using System.Collections.Generic;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class SocketChatController : BaseController
    {
        // GET: SocketChat
        public ActionResult ServiceIndex()
        {
            if (CurrentUser != null)
            {
                ViewBag.UserId = CurrentUser.ID;
                ViewBag.UserName = CurrentUser.UserDisPlayName;
            }
            return View();
        }

        #region 发送消息给微信客户 + ResultModel SendMessageToCustomer(CustomerPoolModel model)
        /// <summary>
        /// 发送消息给微信客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendMessageToCustomer(CustomerPoolModel model)
        {
            if (model == null || string.IsNullOrEmpty(model.OpenId) || string.IsNullOrEmpty(model.Message))
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.ParamError));

            //0、发送给微信客户
            bool resultWx = false;
            string accessToken = WeiXinHelper.GetH5AccessToken();
            //发送文本消息
            if (model.MessageType == MessageTypeEnum.Text)
            {
                resultWx = WeiXinHelper.SendCustomerServiceMessage_Text(model.OpenId, model.Message, accessToken);
            }
            //发送图片消息
            else
            {
                //1、保存图片base64
                string path = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/{3}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, model.OpenId);
                string absulotePath = "";
                model.Message = FileHelper.SaveBase64Image(model.Message, path, out absulotePath);

                //2、上传到微信
                string media_id = WeiXinHelper.UploadTemporaryMedia(accessToken, Senparc.Weixin.MP.UploadMediaFileType.image, System.Web.HttpContext.Current.Server.MapPath(model.Message));
                if (media_id == null)
                    LogHelper.WriteLog("上传微信临时图片失败:图片地址：" + model.Message, LogType.remark);
                //3、发送给用户
                //string domain = System.Web.HttpContext.Current.Request.Url.Host;
                //string url = "http://" + domain + model.Message;
                else
                    resultWx = WeiXinHelper.SendCustomerServiceMessage_Image(model.OpenId, media_id, accessToken);
            }
            if (resultWx)
            {
                //1、保存到数据库
                WeiXinChatRecord re = ServiceFactory.WeiXinChatRecordServiceInstance.AddEntities(new WeiXinChatRecord()
                {
                    Message = model.Message,
                    MessageSource = (short)WeiXinChatRecordMessageSourceEnum.Service,
                    OpenId = model.OpenId,
                    MessageType = (short)model.MessageType,
                    CreateTime = model.Time,
                    CustomerServiceId = CurrentUser.ID
                });

                return Json(new ResultModel(true, "发送成功", CodeStateEnum.Success));

            }
            else
            {
                LogHelper.WriteLog("发送消息给微信客户失败：" + JsonConvert.SerializeObject(model), LogType.remark);
                return Json(new ResultModel(false, "发送失败", CodeStateEnum.Failed));
            }

        }
        #endregion

        #region 获取聊天记录 + ActionResult GetChatRecord(string openId)
        /// <summary>
        /// 获取聊天记录
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public ActionResult GetChatRecord(WeiXinChatRecordParam param)
        {
            //DateTime dt = DateTime.Now.AddDays(-30);
            //var data = ServiceFactory.WeiXinChatRecordServiceInstance.LoadEntities(t => t.OpenId == openId && t.CreateTime > dt)
            //    .Select(o => new
            //    {
            //        Message = o.Message,
            //        MessageType = o.MessageType,
            //        MessageSource = o.MessageSource,
            //        CreateTime = o.CreateTime,
            //        UserDisPlayName = o.SystemUser.UserDisPlayName,
            //        NickName = o.WeiXinUserInfo.NickName,
            //        HeadLogo = o.WeiXinUserInfo.HeadLogo
            //    }).ToList();
            int total = 0;
            param.iSorts = "CreateTime DESC";
            var data = ServiceFactory.WeiXinChatRecordServiceInstance.GetPagingList(param, out total).Select(o => new
            {
                ID = o.ID,
                Message = o.Message,
                MessageType = o.MessageType,
                MessageSource = o.MessageSource,
                CreateTime = o.CreateTime,
                UserDisPlayName = o.SystemUser.UserDisPlayName,
                NickName = o.WeiXinUserInfo.NickName,
                RealName = o.WeiXinUserInfo.RealName,
                HeadLogo = o.WeiXinUserInfo.HeadLogo
            }).ToList().OrderBy(a => a.CreateTime);

            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = data
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取客户备注信息 + ActionResult GetUserRemark(string openId)
        [HttpGet]
        public ActionResult GetUserRemark(string openId)
        {
            if (string.IsNullOrEmpty(openId))
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var result = ServiceFactory.WeiXinUserInfoServiceInstance.LoadEntities(t => t.OpenId == openId).Select(o => new
            {
                RealName = o.RealName,
                Remark = o.Remark,
                Phone = o.Phone,
            }).FirstOrDefault();
            return Json(new ResultModel(true, "获取成功。", CodeStateEnum.Success, result), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 添加客户备注 + ActionResult AddUserRemark(WeiXinUserRemark remark)
        /// <summary>
        /// 添加客户备注
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddUserRemark(WeiXinUserRemark model)
        {
            if (model == null || string.IsNullOrEmpty(model.OpenId))
            {
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            }
            if (string.IsNullOrEmpty(model.RealName) && string.IsNullOrEmpty(model.Remark) && string.IsNullOrEmpty(model.Phone))
            {
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            }

            //添加姓名和备注
            WeiXinUserInfo userinfo = ServiceFactory.WeiXinUserInfoServiceInstance.LoadEntities(t => t.OpenId == model.OpenId).FirstOrDefault();
            if (userinfo == null)
            {
                userinfo = new WeiXinUserInfo();
                userinfo.OpenId = model.OpenId;
                userinfo.Remark = model.Remark;
                userinfo.Phone = model.Phone;
                userinfo.RealName = model.RealName;
                ServiceFactory.WeiXinUserInfoServiceInstance.AddEntities(userinfo);
            }
            else
            {
                userinfo.Remark = model.Remark;
                userinfo.RealName = model.RealName;
                userinfo.Phone = model.Phone;
                userinfo.Updateby = CurrentUser != null ? CurrentUser.UserAccount : "";
                userinfo.UpdateTime = DateTime.Now;
                ServiceFactory.WeiXinUserInfoServiceInstance.UpdateEntities(userinfo);
            }
            return Json(new ResultModel(true, "添加备注成功", CodeStateEnum.Success), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取用户关联的报案单号列表 + ActionResult GetUserOrderList(string openId)
        [HttpGet]
        public ActionResult GetUserOrderList(string openId)
        {
            if (string.IsNullOrEmpty(openId))
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var result = (from a in ServiceFactory.WeiXinUserInsuranceOrderServiceInstance.LoadEntities(t => t.OpenId == openId)
                          join b in ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadEntities(t => true) on a.WarrantyRecordId equals b.ID into temp1
                          from c in temp1.DefaultIfEmpty()
                          select new
                          {
                              WarrantyRecordNo = c.WarrantyRecordNo
                          }).ToList();

            return Json(new ResultModel(true, "获取成功。", CodeStateEnum.Success, result), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 关联报案单号 + ActionResult AssociatedWarrantyRecordNo(WeiXinUserInsuranceOrderParam param)
        /// <summary>
        /// 关联报案单号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AssociatedWarrantyRecordNo(WeiXinUserInsuranceOrderParam param)
        {
            if (param == null || string.IsNullOrEmpty(param.OpenId) || string.IsNullOrEmpty(param.WarrantyRecordNo))
            {
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            }

            //查询报案单号
            InsuranceWarrantyRecord order = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadEntities(t => t.WarrantyRecordNo == param.WarrantyRecordNo).FirstOrDefault();
            if (order == null)
                return Json(new ResultModel(false, "报案单号不存在！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);

            WeiXinUserInsuranceOrder orderRela = ServiceFactory.WeiXinUserInsuranceOrderServiceInstance.LoadEntities(t => t.OpenId == param.OpenId && t.WarrantyRecordId == order.ID).FirstOrDefault();
            if (orderRela != null)
            {
                return Json(new ResultModel(false, "已存在关联信息！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            }

            long id = ServiceFactory.WeiXinUserInsuranceOrderServiceInstance.AddEntities(new WeiXinUserInsuranceOrder { WarrantyRecordId = order.ID, OpenId = param.OpenId, CreateTime = DateTime.Now }).ID;

            if (id < 1)
                return Json(new ResultModel(false, "关联失败！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);

            return Json(new ResultModel(true, "关联成功", CodeStateEnum.Success), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取最近会话用户 + ActionResult GetBeforeChatUser(string name)
        public ActionResult GetBeforeChatUser(string name)
        {
            long currentService = CurrentUser.ID;
            var whereExpression = PredicateExtensions.True<WeiXinChatRecord>();
            //whereExpression = whereExpression.And(o => o.CustomerServiceId == currentService);
            DateTime dt = DateTime.Now.AddDays(-1);
            whereExpression = whereExpression.And(o => o.CreateTime > dt);
            //昵称或真实姓名
            if (!string.IsNullOrEmpty(name))
                whereExpression = whereExpression.And(o => o.WeiXinUserInfo.RealName.Contains(name) || o.WeiXinUserInfo.NickName.Contains(name));

            var data = ServiceFactory.WeiXinChatRecordServiceInstance.LoadEntities(whereExpression).OrderByDescending(t => t.ID).Select(o => new CustomerBaseInfo
            {
                RealName = o.WeiXinUserInfo.RealName,
                NickName = o.WeiXinUserInfo.NickName,
                HeadLogo = o.WeiXinUserInfo.HeadLogo,
                OpenId = o.WeiXinUserInfo.OpenId,
                Remark = o.WeiXinUserInfo.Remark
            }).Distinct().ToList();
            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, data), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 微信用户列表 + ActionResult WeiXinUserList()
        public ActionResult WeiXinUserList()
        {

            return View();
        }
        [HttpPost]
        public ActionResult GetWeiXinUserList(WeiXinUserListModel model)
        {
            var total = 0;
            model.iSorts = "CreateTime desc";
            var data = ServiceFactory.WeiXinUserInfoServiceInstance.GetPagingList(model, out total).Select(o => new
            {
                RealName = o.RealName,
                NickName = o.NickName,
                Remark = o.Remark,
                Phone = o.Phone,
                OpenId = o.OpenId,
                WarrantyRecordNoList ="" //o.WeiXinUserInsuranceOrder.Select(a => new { WarrantyRecordNo = a.InsuranceWarrantyRecord.WarrantyRecordNo })
            }).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = data
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取用户的报案单号 + ActionResult GetUserReportNumber(string openId)
        public ActionResult GetUserReportNumber(string openId)
        {
            if (string.IsNullOrEmpty(openId))
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            List<Byte> list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetStatusList(InsuranceWarrantyRecordTaskType.ToBeProcess);
            var data = (from a in ServiceFactory.WeiXinUserInsuranceOrderServiceInstance.LoadEntities(o => o.OpenId == openId)
                    join b in ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadEntities(o=>list.Contains(o.Status)) on a.WarrantyRecordId equals b.ID into temp1
                    from c in temp1.DefaultIfEmpty()
                    select new
                  {
                      WarrantyRecordNo = c.WarrantyRecordNo,
                      CreateTime = c.CreateTime,
                      ID = c.ID,
                  }).ToList();

            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, data), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 收集资料 + ActionResult CollectData(CollectOrderDataModel model)
        [HttpPost]
        public ActionResult CollectData(CollectOrderDataModel model)
        {
            if (model == null ||
                model.ID < 1 ||
                string.IsNullOrEmpty(model.OpenId) ||
                string.IsNullOrEmpty(model.WarrantyRecordNo) ||
                string.IsNullOrEmpty(model.FileinfoType) ||
                model.ImagesUrl == null ||
                model.ImagesUrl.Count() < 1
                )
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed));

            EnumHelper enumHelper = EnumHelper.Instance;
            string imageTypeName = enumHelper.GetDescription(typeof(WarrantyRecordImageEnums), model.FileinfoType);

            InsuranceWarrantyRecord entityRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
            //1、把图片移动到别的文件夹——下载已处理任务的时候需要压缩图片，下载文件（保存路径与/InsuranceWarrantyRecordController/SaveIWRImages下的一致）
            string folderName = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/{3}_{4}_{5}/{6}/", entityRecord.CreateTime.Year, entityRecord.CreateTime.Month, entityRecord.CreateTime.Day, entityRecord.Reporter, entityRecord.ReporterPhone.Trim(), entityRecord.WarrantyRecordNo, imageTypeName);

            string message = "";
            var entity = new InsuranceWarrantyRecordImages { InsuranceWarrantyRecordId = model.ID };
            for (int i = 0; i < model.ImagesUrl.Count(); i++)
            {
                var iwrImage = model.ImagesUrl[i];
                string fileName = System.Guid.NewGuid().ToString() + ".png";
                bool isOk = FileHelper.MoveFile(System.Web.HttpContext.Current.Server.MapPath(iwrImage), System.Web.HttpContext.Current.Server.MapPath(folderName), fileName);
                if (iwrImage != null && isOk)
                {
                    //新增素材
                    entity.FileName = fileName;
                    entity.FilePath = folderName + fileName;
                    entity.FileSize = "0";
                    entity.IsAvailable = true;
                    entity.CreateBy = CurrentUser.UserAccount;
                    entity.CreateTime = DateTime.Now;
                    entity.ImageType = Convert.ToByte(model.FileinfoType); //资料类型
                    ServiceFactory.InsuranceWarrantyRecordImagesServiceInstance.AddEntities(entity);
                    long weiXinChatRecordID = model.WeiXinChatRecordID[i];
                    //修改聊天记录的地址
                    WeiXinChatRecord re = ServiceFactory.WeiXinChatRecordServiceInstance.LoadEntities(o => o.ID == weiXinChatRecordID).FirstOrDefault();
                    re.Message = folderName + fileName;
                    ServiceFactory.WeiXinChatRecordServiceInstance.UpdateEntities(re);
                }
                else
                {
                    message += "关联出错：" + iwrImage + "；\r\n";
                }
            }

            if (string.IsNullOrEmpty(message))
                return Json(new ResultModel(true, "关联成功", CodeStateEnum.Success));
            else
                return Json(new ResultModel(false, message, CodeStateEnum.Failed));
        }
        #endregion
    }
}